﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using VideoRentalShop.Model;

namespace VideoRentalShop.Controller.Data
{
    public class OrderDetailsDataSource : DataSourceBase<OrderDetails>
    {
        public OrderDetailsDataSource(MovieDbContext db) : base(db) { }


        public DbSet<OrderDetails> GetAll()
        {
            return _db.OrderDetails;
        }


        public override bool IsValid(OrderDetails item)
        {
            return _db.Entry(item).GetValidationResult().IsValid;
        }

        public override bool Add(OrderDetails item)
        {
            var entry = _db.Entry<OrderDetails>(item);
            var valid = entry.GetValidationResult().IsValid;
            if (valid)
            {
                entry.State = EntityState.Added;
                return Save();
            }

            return valid;
        }

        public override bool Edit(OrderDetails item)
        {
            var entry = _db.Entry<OrderDetails>(item);
            var valid = entry.GetValidationResult().IsValid;
            if (valid)
            {
                entry.State = EntityState.Modified;
                return Save();
            }

            return valid;
        }

        public override bool Remove(OrderDetails item)
        {
            var result = _db.OrderDetails.Find(item);
            if (result != null)
            {
                SetRemoved(result);
                return Save();
            }

            return false;
        }
        
        public bool Remove(Order item)
        {
            if (item != null)
            {
                var list = item.OrderDetails;
                if (list.Count > 0)
                {
                    var test = list.Count;
                    for (var i = 0; i < test; ++i)
                    {
                        SetRemoved(list[0]);
                    }

                    return Save();
                }

                return true;
            }

            return false;
        }
        
        public bool Remove(Movie item)
        {
            var list = item.Orders;
            if (item != null && list.Count > 0)
            {
                var test = list.Count;
                for (var i = 0; i < test; ++i)
                {
                    SetRemoved(list[0]);
                }
                return Save();
            }

            return false;
        }

        private void SetRemoved(OrderDetails item)
        {
            if (!item.Order.Archived && item.ReturnDate == null)
            {
                ++item.Movie.Avaiable;
                _db.Entry(item.Movie).State = EntityState.Modified;
            }
            _db.Entry(item).State = EntityState.Deleted;
        }
    }
}
